import 'dart:convert';

import 'package:cached_network_image/cached_network_image.dart';
import 'package:fluro/fluro.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_easyrefresh/easy_refresh.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:ugrownews_flutter/main/ScreenNewsDetail.dart';
import 'package:ugrownews_flutter/utils/RouterUtil.dart';
import 'package:ugrownews_flutter/utils/TextUtil.dart';
import 'package:ugrownews_flutter/utils/UGrowColors.dart';
import 'package:ugrownews_flutter/utils/netutil/NetUtil.dart';
import 'package:ugrownews_flutter/utils/netutil/NewsNetUtil.dart';

class ScreenSearchResult extends StatefulWidget {
  String keyWord = "";

  ScreenSearchResult({key, @required this.keyWord}) : super(key: key);

  @override
  _ScreenSearchResultState createState() => _ScreenSearchResultState();
}

class _ScreenSearchResultState extends State<ScreenSearchResult> {
  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    _initData(this, 1, 20);
  }

  Future<dynamic> _initData(
      //初始化数据
      _ScreenSearchResultState _screenSearchResultState,
      int page,
      int pageSize) {
    Map<String, String> params = new Map();
    params["page"] = page.toString();
    params["pageSize"] = pageSize.toString();
    params["keyWord"] = widget.keyWord;
    return new NewsNetUtil().searchNewsList(params, (result, isCache) {
      _screenSearchResultState.isLoading = false;
      if (result is NetError) {
        return;
      } else {
        Map jsonResult = json.decode(result);
        String state = jsonResult["state"];
        if (state.isNotEmpty && state == "success") {
          if (_screenSearchResultState.mounted) {
            _screenSearchResultState.setState(() {
              List<dynamic> data = jsonResult["data"];
              if (page == 1) {
                if (data.length == 0) {
                  _screenSearchResultState.page = 0;
                } else {
                  _screenSearchResultState.data = data;
                }
              } else {
                _screenSearchResultState.data.addAll(data);
              }
            });
          }
        }
      }
    });
  }

  List<dynamic> data = new List();
  int page = 1;
  bool isLoading = false;

  ScrollController controller = new ScrollController();
  GlobalKey<EasyRefreshState> _easyRefreshKey =
      new GlobalKey<EasyRefreshState>();

  @override
  Widget build(BuildContext context) {
    return new Scaffold(
      body: new Stack(
        children: <Widget>[
          //顶部导航，包含通知栏高度
          new Positioned(
            height: ScreenUtil.instance.setWidth(118) +
                MediaQuery.of(context).padding.top,
            width: ScreenUtil.screenWidthDp,
            child: new Container(
              color: UGrowColors.getColor("#dff1fd"),
              child: new Stack(
                alignment: Alignment.center,
                children: <Widget>[
                  //底部渐变背景
                  new Container(
                    margin: EdgeInsets.only(
                        top: MediaQuery.of(context).padding.top),
                    width: ScreenUtil.screenWidthDp,
                    height: ScreenUtil.instance.setWidth(118),
                    decoration: new BoxDecoration(
                        gradient: new LinearGradient(
                            begin: Alignment.topCenter,
                            end: Alignment.bottomCenter,
                            colors: [
                          UGrowColors.getColor("#dff1fd"),
                          UGrowColors.getColor("#84dce6"),
                        ])),
                  ),
                  //返回按钮
                  new Positioned(
                    left: 0,
                    top: MediaQuery.of(context).padding.top,
                    height: ScreenUtil.getInstance().setWidth(118),
                    width: ScreenUtil.getInstance().setWidth(140),
                    child: new GestureDetector(
                      child: new Container(
                        padding: EdgeInsets.all(
                            ScreenUtil.getInstance().setWidth(15)),
                        margin: EdgeInsets.only(
                            left: ScreenUtil.getInstance().setWidth(5)),
                        child: new Image.asset(
                          "images/detail_back.png",
                          fit: BoxFit.fill,
                        ),
                      ),
                      onTap: () {
                        Navigator.pop(context);
                      },
                    ),
                  ),
                  //中间标题
                  new Container(
                    margin: EdgeInsets.only(
                      top: MediaQuery.of(context).padding.top,
                    ),
                    height: ScreenUtil.getInstance().setWidth(66),
                    child: new Text(
                      "搜索结果",
                      style: new TextStyle(
                          fontSize: ScreenUtil.getInstance().setWidth(60),
                          color: Colors.black),
                    ),
                  ),
                ],
              ),
            ),
          ),
          //WebView
          new Positioned(
            top: MediaQuery.of(context).padding.top +
                ScreenUtil.instance.setWidth(118),
            bottom: MediaQuery.of(context).padding.bottom,
            width: ScreenUtil.screenWidthDp,
            //用数据长度和页码判断状态
            // 在第一页数据长度为0 时，将页码置零，
            child: data.length > 0
                ? new EasyRefresh(
                    key: _easyRefreshKey,
                    onRefresh: _onRefresh,
                    loadMore: _loadMore,
                    child: new ListView.builder(
                      controller: controller,
                      padding: EdgeInsets.all(0),
                      itemCount: data.length,
                      itemBuilder: _buildItem,
                    ),
                  )
                : page > 0
                    ? new Center(
                        child: new GestureDetector(
                          child: new Text("正在加载"),
                          onTap: () {
                            _initData(this, page, 10);
                          },
                        ),
                      )
                    : new Center(
                        child: new GestureDetector(
                          child: new Text("暂无数据"),
                          onTap: () {
                            _initData(this, page, 10);
                          },
                        ),
                      ),
          ),
        ],
      ),
    );
  }

  Future<dynamic> _onRefresh() {
    if (!isLoading) {
      isLoading = true;
      page = 1;
      return _initData(this, page, 10);
    }
  }

  Future<dynamic> _loadMore() async {
    if (!isLoading) {
      isLoading = true;
      page++;
      return _initData(this, page, 10);
    }
  }

  //构建条目
  Widget _buildItem(BuildContext context, int index) {
    Widget item;
    switch (data[index]["customType"]) {
      case 0:
        item = _createSingleImageItem(data[index]);
        break;
      case 1:
        item = _createSingleImageTitleItem(data[index]);
        break;
      case 2:
        item = _createThreeImageItem(data[index]);
        break;
      default:
        item = _createSingleImageItem(data[index]);
        break;
    }
    //给item添加GestureDetector，点击跳转详情页
    return new GestureDetector(
      child: item,
      onTap: () {
        RouterUtil.getInstance().navigateTo(
            context,
            RouterUtil.ROUTER_NEWSDETAIL +
                "?id=" +
                data[index]["id"].toString(),
            transition: TransitionType.cupertino,);
      },
    );
  }

  @override
  bool get wantKeepAlive => true;

  //单张图Item
  Widget _createSingleImageItem(data) {
    return new Container(
      height: ScreenUtil.getInstance().setWidth(222 + 28 + 29),
      width: ScreenUtil.screenWidthDp,
      padding: new EdgeInsets.only(
          left: ScreenUtil.getInstance().setWidth(36),
          right: ScreenUtil.getInstance().setWidth(36),
          top: ScreenUtil.getInstance().setWidth(28)),
      child: new Stack(
        children: <Widget>[
          new CachedNetworkImage(
            imageUrl: data["customImage"],
            placeholder: (context, url) {
              return new Image.asset(
                "images/image_loading1.png",
                height: ScreenUtil.getInstance().setWidth(222),
                width: ScreenUtil.getInstance().setWidth(294),
                fit: BoxFit.fill,
              );
            },
            errorWidget: (context, url, builder) {
              return new Icon(Icons.error);
            },
            height: ScreenUtil.getInstance().setWidth(222),
            width: ScreenUtil.getInstance().setWidth(294),
            fit: BoxFit.fill,
          ),
          new Positioned(
            width: ScreenUtil.screenWidthDp -
                ScreenUtil.getInstance().setWidth(360) -
                ScreenUtil.getInstance().setWidth(36),
            left: ScreenUtil.getInstance().setWidth(360 - 36),
            child: new Text(
              data["title"],
              maxLines: 2,
              softWrap: true,
              overflow: TextOverflow.ellipsis,
              style: new TextStyle(
                  color: UGrowColors.getColor("#333333"),
                  fontSize: ScreenUtil.getInstance().setWidth(48)),
            ),
          ),
          new Positioned(
            bottom: ScreenUtil.getInstance().setWidth(28),
            child: new Text(
              getPublishDate(data),
              maxLines: 1,
              style: new TextStyle(
                  color: UGrowColors.getColor("#999999"),
                  fontSize: ScreenUtil.getInstance().setWidth(38)),
            ),
            left: ScreenUtil.getInstance().setWidth(330),
          ),
          new Positioned(
            bottom: 0,
            height: ScreenUtil.getInstance().setWidth(2),
            child: new Container(
              height: ScreenUtil.getInstance().setWidth(2),
              width: ScreenUtil.screenWidthDp -
                  ScreenUtil.getInstance().setWidth(36 + 36),
              color: UGrowColors.getColor("#cccccc"),
            ),
          ),
        ],
      ),
    );
  }

  //单张大图Item
  Widget _createSingleImageTitleItem(data) {
    return new Container(
      width: ScreenUtil.screenWidthDp,
      child: new Column(
        children: <Widget>[
          new Container(
            alignment: Alignment.centerLeft,
            height: ScreenUtil.getInstance().setWidth(450),
            margin: new EdgeInsets.only(
              top: ScreenUtil.getInstance().setWidth(40),
              left: ScreenUtil.getInstance().setWidth(36),
              right: ScreenUtil.getInstance().setWidth(36),
            ),
            width: ScreenUtil.screenWidthDp -
                ScreenUtil.getInstance().setWidth(36 + 36),
            child: new CachedNetworkImage(
              imageUrl: data["customImage"],
              placeholder: (context, url) {
                return new Image.asset(
                  "images/image_loading1.png",
                  height: ScreenUtil.getInstance().setWidth(608),
                  width: ScreenUtil.screenWidthDp,
                  fit: BoxFit.fill,
                );
              },
              errorWidget: (context, url, builder) {
                return new Icon(Icons.error);
              },
              height: ScreenUtil.getInstance().setWidth(608),
              width: ScreenUtil.screenWidthDp,
              fit: BoxFit.fill,
            ),
          ),
          new Container(
            margin: new EdgeInsets.only(
              top: ScreenUtil.getInstance().setWidth(40),
              left: ScreenUtil.getInstance().setWidth(36),
              right: ScreenUtil.getInstance().setWidth(36),
            ),
            width: ScreenUtil.screenWidthDp -
                ScreenUtil.getInstance().setWidth(36 + 36),
            child: new Text(
              data["title"],
              maxLines: 1,
              softWrap: true,
              overflow: TextOverflow.ellipsis,
              textAlign: TextAlign.left,
              style: new TextStyle(
                color: UGrowColors.getColor("#333333"),
                fontSize: ScreenUtil.getInstance().setWidth(48),
              ),
            ),
          ),
          new Container(
            margin: new EdgeInsets.only(
              top: ScreenUtil.getInstance().setWidth(36),
              left: ScreenUtil.getInstance().setWidth(36),
              right: ScreenUtil.getInstance().setWidth(36),
            ),
            width: ScreenUtil.screenWidthDp -
                ScreenUtil.getInstance().setWidth(36 + 36),
            child: new Text(
              getPublishDate(data),
              maxLines: 1,
              softWrap: true,
              textAlign: TextAlign.left,
              style: new TextStyle(
                color: UGrowColors.getColor("#999999"),
                fontSize: ScreenUtil.getInstance().setWidth(38),
              ),
            ),
          ),
          new Container(
            margin: new EdgeInsets.only(
              bottom: 0,
              top: ScreenUtil.getInstance().setWidth(26),
            ),
            height: ScreenUtil.getInstance().setWidth(2),
            child: new Container(
              height: ScreenUtil.getInstance().setWidth(2),
              width: ScreenUtil.screenWidthDp -
                  ScreenUtil.getInstance().setWidth(36 + 36),
              color: UGrowColors.getColor("#cccccc"),
            ),
          ),
        ],
      ),
    );
  }

  //三张图Item
  Widget _createThreeImageItem(data) {
    List<String> imageList = ((data["customImage"]) as String).split(",");
    return new Container(
      child: new Column(
        children: <Widget>[
          new Container(
            margin: new EdgeInsets.only(
              left: ScreenUtil.getInstance().setWidth(36),
              right: ScreenUtil.getInstance().setWidth(36),
              top: ScreenUtil.getInstance().setWidth(28),
            ),
            width: ScreenUtil.screenWidthDp -
                ScreenUtil.getInstance().setWidth(36 + 36),
            child: new Text(
              data["title"],
              maxLines: 1,
              softWrap: true,
              overflow: TextOverflow.ellipsis,
              style: new TextStyle(
                  color: UGrowColors.getColor("#333333"),
                  fontSize: ScreenUtil.getInstance().setWidth(48)),
            ),
          ),
          new Container(
            height: ScreenUtil.getInstance().setWidth(240),
            margin: new EdgeInsets.only(
              top: ScreenUtil.getInstance().setWidth(18),
              left: ScreenUtil.getInstance().setWidth(35),
            ),
            child: new Row(
              children: <Widget>[
                new Container(
                  child: new CachedNetworkImage(
                    imageUrl: imageList[0],
                    placeholder: (context, url) {
                      return new Image.asset(
                        "images/image_loading1.png",
                        height: ScreenUtil.getInstance().setWidth(240),
                        width: ScreenUtil.getInstance().setWidth(320),
                        fit: BoxFit.fill,
                      );
                    },
                    errorWidget: (context, url, builder) {
                      return new Icon(Icons.error);
                    },
                    height: ScreenUtil.getInstance().setWidth(240),
                    width: ScreenUtil.getInstance().setWidth(320),
                    fit: BoxFit.fill,
                  ),
                ),
                new Container(
                  margin: new EdgeInsets.only(
                    left: ScreenUtil.getInstance().setWidth(26),
                  ),
                  child: new CachedNetworkImage(
                    imageUrl: imageList[1],
                    placeholder: (context, url) {
                      return new Image.asset(
                        "images/image_loading1.png",
                        height: ScreenUtil.getInstance().setWidth(240),
                        width: ScreenUtil.getInstance().setWidth(320),
                        fit: BoxFit.fill,
                      );
                    },
                    errorWidget: (context, url, builder) {
                      return new Icon(Icons.error);
                    },
                    height: ScreenUtil.getInstance().setWidth(240),
                    width: ScreenUtil.getInstance().setWidth(320),
                    fit: BoxFit.fill,
                  ),
                ),
                new Container(
                  margin: new EdgeInsets.only(
                    left: ScreenUtil.getInstance().setWidth(26),
                  ),
                  child: new CachedNetworkImage(
                    imageUrl: imageList[2],
                    placeholder: (context, url) {
                      return new Image.asset(
                        "images/image_loading1.png",
                        height: ScreenUtil.getInstance().setWidth(240),
                        width: ScreenUtil.getInstance().setWidth(320),
                        fit: BoxFit.fill,
                      );
                    },
                    errorWidget: (context, url, builder) {
                      return new Icon(Icons.error);
                    },
                    height: ScreenUtil.getInstance().setWidth(240),
                    width: ScreenUtil.getInstance().setWidth(320),
                    fit: BoxFit.fill,
                  ),
                ),
              ],
            ),
          ),
          new Container(
            margin: new EdgeInsets.only(
              top: ScreenUtil.getInstance().setWidth(36),
              left: ScreenUtil.getInstance().setWidth(36),
              right: ScreenUtil.getInstance().setWidth(36),
            ),
            width: ScreenUtil.screenWidthDp -
                ScreenUtil.getInstance().setWidth(36 + 36),
            child: new Text(
              getPublishDate(data),
              maxLines: 1,
              softWrap: true,
              textAlign: TextAlign.left,
              style: new TextStyle(
                color: UGrowColors.getColor("#999999"),
                fontSize: ScreenUtil.getInstance().setWidth(38),
              ),
            ),
          ),
          new Container(
            margin: new EdgeInsets.only(
              bottom: 0,
              top: ScreenUtil.getInstance().setWidth(26),
            ),
            height: ScreenUtil.getInstance().setWidth(2),
            child: new Container(
              height: ScreenUtil.getInstance().setWidth(2),
              width: ScreenUtil.screenWidthDp -
                  ScreenUtil.getInstance().setWidth(36 + 36),
              color: UGrowColors.getColor("#cccccc"),
            ),
          ),
        ],
      ),
    );
  }

  //从data中组合时间副标题的文字，乱的一逼
  String getPublishDate(data) {
    String publishDate = data["publishDate"];
    int year = DateTime.now().year;
    int month = DateTime.now().month;
    int day = DateTime.now().day;
    if (int.parse(publishDate.substring(0, 4)) == year &&
        int.parse(publishDate.substring(5, 7)) == month &&
        int.parse(publishDate.substring(8, 10)) == day) {
      publishDate = publishDate.substring(11, 19);
    } else if (int.parse(publishDate.substring(0, 4)) == year) {
      publishDate = publishDate.substring(5, 10);
    } else {
      publishDate = publishDate.substring(0, 10);
    }

    if (!TextUtil.isEmpty(data["referName"])) {
      publishDate = data["referName"] + " " + publishDate;
    }
    return publishDate;
  }
}
